﻿using System;
using System.Web;
using log4net.Core;
using log4net.Layout.Pattern;

namespace Commons.log
{
    class HttpContextUserPatternConverter : PatternLayoutConverter
    {
        private static ILog log = CommonLog.GetLogger();

        protected override void Convert(System.IO.TextWriter writer, LoggingEvent loggingEvent)
        {
            try
            {
                string name = "";
                HttpContext context = HttpContext.Current;
                if (context != null && context.User != null && context.User.Identity.IsAuthenticated)
                {
                    name = context.User.Identity.Name;
                }
                writer.Write(name);
            }
            catch (Exception e)
            {
                log.Warn(e.Message, e);
                writer.Write("");
            }
        }
    }
}
